package com.skydroid.cv_demo;

import android.content.DialogInterface;
import android.graphics.Rect;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.skydroid.cv.ModelHelper;
import com.skydroid.cv.SkydroidTrackerHelper;
import com.skydroid.fpvplayer.DirectBufferHelper;
import com.skydroid.fpvplayer.FPVWidget;
import com.skydroid.fpvplayer.PlayerType;
import com.skydroid.fpvplayer.RtspTransport;
import com.skydroid.fpvplayer.VideoDecoderCallBack;

import java.nio.ByteBuffer;

/**
 * @author 咔一下
 * @date 2024/10/11 09:56
 * @email 1501020210@qq.com
 */
public class MainActivity extends AppCompatActivity {

    FPVWidget fpvWidget = null;
    DetectionTargetView drawView = null;
    SkydroidTrackerHelper helper = new SkydroidTrackerHelper(); //目标跟踪工具类
    boolean isCanInitTracker = false;
    boolean isInitTracker = false;
    TrackerThread trackerThread = null; //跟踪线程
    byte[] currYuv = null;
    int pixel_format = SkydroidTrackerHelper.PIXEL_FORMAT_YUV420P;
    private int mWidth = 0;
    private int mHeight = 0;
    private final Object lock = new Object();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Settings settings = new Settings(getApplicationContext());
        //初始化CV库
        ModelHelper.load(this);
        //去掉标题栏
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);

        fpvWidget = findViewById(R.id.fpvWidget);

        findViewById(R.id.btnUrl).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String lastUrl = settings.getLastUrl();
                if (TextUtils.isEmpty(lastUrl)){
                    lastUrl = Settings.C10;
                }
                InputUrlDialogFragment.createDialog("确定", new InputUrlDialogFragment.ButtonOnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id, String s) {
                        if (TextUtils.isEmpty(s)){
                            return;
                        }
                        settings.setLastUrl(s);
                        fpvWidget.setUrl(s);
                        fpvWidget.stop();
                        fpvWidget.start();
                    }
                }, "取消", new InputUrlDialogFragment.ButtonOnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id, String s) {

                    }
                },lastUrl).show(getSupportFragmentManager(),"action_url");
            }
        });

        fpvWidget.setVideoDecoderCallBack(new VideoDecoderCallBack() {
            @Override
            public void onYUV(@NonNull ByteBuffer data, int width, int height, int pixel_format) {
                if (currYuv == null){
                    currYuv = new byte[data.capacity()];
                    mWidth = width;
                    mHeight = height;
                    MainActivity.this.pixel_format = pixel_format;
                }
                if (mWidth != width || mHeight != height){
                    mWidth = width;
                    mHeight = height;
                    currYuv = new byte[data.capacity()];
                }
                synchronized(lock){
                    data.rewind();
                    data.get(currYuv);
                }
            }
        });
        drawView = findViewById(R.id.drawView);
        drawView.setConfirmTargetCallBack(new DetectionTargetView.OnConfirmTargetCallBack() {
            @Override
            public void onClearTarget() {
                isInitTracker = false;
                isCanInitTracker = false;
            }

            @Override
            public void onConfirmTarget(int viewWidth, int viewHeight, Rect target) {
                isCanInitTracker = true;
            }
        });

        String url = settings.getLastUrl();

        //使用硬解
        fpvWidget.setUsingMediaCodec(true);
        //使用软解
//        fpvWidget.setUsingMediaCodec(false);

        //设置播放地址
        fpvWidget.setUrl(TextUtils.isEmpty(url) ? Settings.C10 : url);

        //使用云卓播放器（只能使用云卓播放器才能通过setVideoDecoderCallBack读到YUV数据）
        fpvWidget.setPlayerType(PlayerType.ONLY_SKY);

        //RTSP流TCP/UDP连接
        fpvWidget.setRtspTranstype(RtspTransport.AUTO);

        //开始播放
        fpvWidget.start();

        //创建跟踪器
        helper.createTracker(
                SkydroidTrackerHelper.TRACKER_TYPE_NANO,
                ModelHelper.getTrackNanoV2Args(this)
        );

        if (trackerThread != null){
            trackerThread.interrupt();
        }
        //开启跟踪线程
        trackerThread = new TrackerThread();
        trackerThread.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        fpvWidget.stop();
        //释放跟踪器
        helper.releaseTracker();

        //关闭跟踪线程
        trackerThread.interrupt();
        trackerThread = null;
    }

    class TrackerThread extends Thread {

        private boolean isRun = false;

        @Override
        public void run() {
            super.run();
            isRun = true;
            while (isRun){
                try {
                    byte[] currYuv = MainActivity.this.currYuv;
                    ByteBuffer yuv = null;
                    synchronized(lock){
                        if (currYuv != null){
                            yuv = DirectBufferHelper.createDirectBuffer(currYuv.length);
                            yuv.put(currYuv);
                        }
                    }
                    int width = mWidth;
                    if (width == 0){
                        continue;
                    }
                    int height = mHeight;
                    if (height == 0){
                        continue;
                    }
                    if (yuv == null){
                        continue;
                    }
//                    MyLogger.kLog().e("目标跟随线程运行中 --- ${isInitTracker} ${isCanInitTracker}")
                    if (!isInitTracker && isCanInitTracker) {
                        Rect rect = drawView.getTargetRect();
                        float sw = (float)width / drawView.getMeasuredWidth();
                        float sh = (float)height / drawView.getMeasuredHeight();
                        int x = (int)(rect.left * sw);
                        int y = (int)(rect.top * sh);
                        //设置跟踪目标
                        isInitTracker = helper.setTarget(
                                yuv,
                                width,
                                height,
                                pixel_format,
                                x,
                                y,
                                (int) (rect.width() * sw),
                                (int) (rect.height() * sh)
                        );
                    }
                    if (isInitTracker) {
                        //检测跟踪目标
                        Rect rect = helper.detectionTarget(yuv, width, height,pixel_format);
                        if (rect != null && helper.getTrackingScore() >= 70) {
                            float sw = (float)width / drawView.getMeasuredWidth();
                            float sh = (float)height / drawView.getMeasuredHeight();
                            int x1 = (int)(rect.left / sw);
                            int y1 = (int)(rect.top / sh);
                            int x2 = (int)(rect.right / sw);
                            int y2 = (int)(rect.bottom / sh);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    drawView.updateRect(new Rect(x1, y1, x2, y2));
                                }
                            });
                        }
                    }
                    DirectBufferHelper.deleteDirectBuffer(yuv);
                }catch (Exception e){
                }
            }
        }

        @Override
        public void interrupt() {
            super.interrupt();
            isRun = false;
        }

    }
}
